package com.wsllx.controller;

//import com.wsllx.mapper.TestMapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wsllx.entity.User;
import com.wsllx.mapper.UserMapper;
import com.wsllx.service.UserServiceImpl;
import com.wsllx.util.ExelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liulx
 * @date 2022-08-30
 * @description 用户表测试
 */
//@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ExelUtil exelUtil;

    /**
     * 测试连接
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/insert")
    public String insert() throws Exception {
        User user = new User();
        user.setName("jzm");
        int insert = userMapper.insert(user);
        return user.toString();
    }

    @RequestMapping("/delete")
    public String delete(@RequestBody User user) throws Exception {
        if (null == user) {
            throw new Exception("传入对象不能为空");
        }
        LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<>();
        lambda.eq(User::getId, user.getId());
        int delete = userMapper.delete(lambda);
        return "删除成功";
    }

    @RequestMapping("/get")
    public String get(@RequestBody User user) throws Exception {
        if (null == user) {
            throw new Exception("传入对象不能为空");
        }
        LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<>();
        lambda.eq(User::getId, user.getId());
        User user1 = userService.getOne(lambda);
        return user1.toString();
    }

    /**
     * 下载exel
     *
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("exel")
    public String exel(HttpServletResponse response) throws Exception {
        OutputStream os = null;
        try {
            // 设置返回内容类型与header
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=odsExport-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls");
            os = response.getOutputStream();
            // String path = "D:\\temp\\output.xlsx";
            // 写入字节到os文件流
            exelUtil.getStream("/bmoTemplate.xlsx", os);
            return "执行成功";
        } catch (Exception e) {
            logger.info("导出excel异常");
        } finally {
            os.flush();
            os.close();
        }

        return "执行成功";
    }

}
